package com.authine.cloudpivot.ext.sso;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.web.sso.security.BaseAuthenticationToken;
import com.authine.cloudpivot.web.sso.template.BaseSimpleTemplate;
import com.authine.cloudpivot.web.sso.template.ResponseTypeEnum;
import com.authine.cloudpivot.web.sso.template.SimpleTemplateConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import com.authine.cloudpivot.web.api.utils.HttpClientUtils;

import java.util.HashMap;
import java.util.Map;

//qxwz/login
@Component
@Slf4j
public class QxwzConfig extends BaseSimpleTemplate {

    @Value("${custom.bucUrl}")
    private String bucUrl ;
    @Value("${custom.bucAuthToken:buc-auth-token}")
    private String bucAuthToken ;

    QxwzConfig() {
        super(SimpleTemplateConfig.builder()
                .requestMatcher(new AntPathRequestMatcher("/qxwz/login", HttpMethod.GET.name()))
                .responseType(ResponseTypeEnum.JSON)
                .redirectClientID("api")    //云枢OAuth2登录的ClientId  具体体现在base_security_client表中
                //成功后回调地址   会优先从url中获取redirect_uri，login_fail_redirect_uri。若url中无法携带，可使用默认配置 http://120.24.79.179/admin/#/apps/model/harry/aaa/dispatcher 需要在后台添加白名单
                ///oauth/authorize?client_id=api&response_type=code&scope=read为固定
//                .loginPassredirectUrl("http://120.24.79.179/api/oauth/authorize?client_id=api&response_type=code&scope=read&redirect_uri=http://120.24.79.179/admin/#/apps/model/harry/aaa/dispatcher")
                .loginFailRedirectUri("http://passport.wz-inc.com/sso.html?return_url=http://192.168.248.153")
                .build());
    }

    @Override
    public String getSourceId(BaseAuthenticationToken token) throws Exception {
        System.out.println( "千寻位置");
        String code = token.getCode();
        if (code == null) {
            return "不存在";
        }
        Map<String, String> header = new HashMap<>();
        header.put(bucAuthToken,code);
        String str = HttpClientUtils.doGet(bucUrl, header);

        if (log.isDebugEnabled()) {
            log.debug("buc验证，获取用户信息 str ：{}",str);
        }



        return str;
    }



    @Override
    public UserModel getUser(Object sourceId) {


        JSONObject json = (JSONObject) JSON.parse(String.valueOf(sourceId));
        String email =  null;
        if (json != null && StringUtils.isNotBlank( json.getString("email"))){
            String  emailJson = json.getString("email");
            String[] split = emailJson.split("@");
            email = split[0];

            if (log.isDebugEnabled()) {
                log.debug("buc验证，获取用户信息email：{}",email);
            }
        }
        UserModel user = null;

        if (email != null) {
            user = dubboConfigService.getSystemSecurityFacade().getUserByUsername(email);
            if (user != null) {
                return  user;
            }
        }



        String mobile = json.getString("mobile");

        if (log.isDebugEnabled()) {
            log.debug("buc验证，获取用户信息mobile：{}",mobile);
        }

        if (StringUtils.isNotBlank(mobile)) {
            user = dubboConfigService.getSystemSecurityFacade().getFirstUserByUsernameOrMobile(mobile);
        }

        if (log.isDebugEnabled()) {
            if (user == null) {
                log.debug("buc验证，获取用户信息失败：user 为 null");
            }
        }

        return  user;
       // return dubboConfigService.getSystemSecurityFacade().getUserByUsernameOrMobile(String.valueOf(sourceId));
    }
}